import React, { useEffect, useRef, forwardRef, useState } from 'react';
import { connect } from 'dva';
import { Button, message } from 'antd';
import withRouter from 'umi/withRouter';
import BasicInfo from './../basicInfo';
import Archives from './../archives';
import router from 'umi/router';
import './index.styl';

const BasicInfoRef = forwardRef((props, ref) => <BasicInfo {...props} cRef={ref} />);
const ArchivesRef = forwardRef((props, ref) => <Archives {...props} cRef={ref} />);

function AddLegder({
  dictionaryList: { dicList, groupList },
  dispatch,
  id,
  location,
  deviceLedger: { detail, notNo },
  headerTaps: { panes }
}) {
  const basicInfoRef = useRef();
  const archivesRef = useRef();
  // 初始化设备编号重复
  useEffect(() => {
    dispatch({
      type: 'deviceLedger/changeNoCheck',
    });
  }, [dispatch])
  useEffect(() => {
    // 获取字典
    dispatch({
      type: 'dictionaryList/getList',
    });
    dispatch({
      type: 'dictionaryList/getGroupList',
    });
  }, [dispatch]);
  useEffect(() => {
    if (id !== undefined) {
      dispatch({
        type: 'deviceLedger/getDetail',
        payload: { id },
      });
    }
  }, [id, dispatch])
  const submitData = () => {
    if (!notNo) {
      message.info('设备编号重复，请重新输入！')
      return;
    }
    const { values, deviceImage, validateFields } = basicInfoRef.current;
    if (values.price && values.price[values.price.length - 1] === '.') {
      values.price = values.price + '00'
    }
    validateFields()
      .then(async () => {
        if (!(archivesRef.current.fileName.every(item => item.show === true))) {
          message.info('文件上传中，请稍后提交')
          return
        }
        const arry = [];
        archivesRef.current.fileList.map(i => {
          arry.push({
            fileName: i.name || i.fileName,
            fileType: i.typeCode || i.fileType,
            fileUrl: (i.response && i.response.data && i.response.data.url) || i.fileUrl,
          });
        });
        if (id) {
          const res = await dispatch({
            type: 'deviceLedger/editDevice',
            payload: {
              id: detail.id || '',
              ...values,
              deviceImage: deviceImage || detail.deviceImage,
              deviceFileList: arry ? [...arry] : [...detail.deviceFileList],
            },
          });
          if (res.code === '000000') {
            handleCancle();
          }
        } else {
          const res = await dispatch({
            type: 'deviceLedger/addDevice',
            payload: {
              ...values,
              deviceImage: deviceImage,
              deviceFileList: [...arry],
            },
          });
          if (res.code === '000000') {
            handleCancle();
          }
        }
      })
      .catch(err => {
        console.log(err);
      });
  };

  // 跳转
  function handleCancle() {
    const { pathname } = location
    const panesList = panes.filter(pane => pane.key !== pathname);
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          'deviceLedger_add': [false, true],
          'deviceLedger_edit': [false, true],
        }
      }
    })
    dispatch({
      type: 'deviceLedger/updateSerachParams',
      payload: {
        serachParams: {
          current: 1
        }
      }
    })
    router.push({
      pathname: '/deviceLedger',
      params: { isRefresh: true }
    })
  }
  // 取消按钮直接返回上个页面
  function cancelLink () {
    const { pathname } = location
    const panesList = panes.filter(pane => pane.key !== pathname);
    if (panesList.length === 0) {
      return
    }
    let prevObj = {}
    panes.forEach((item,index) => {
      if (item.key === pathname) {
        if (index) {
          prevObj = panes[index - 1]
        } else {
          prevObj = panes[index + 1]
        }
      }
    })
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          'deviceLedger_add': [false, true],
          'deviceLedger_edit': [false, true],
        }
      }
    })
    router.push({
      pathname: prevObj.path,
      query: prevObj.query
    })
  }

  return (
    <div className="AddDeviceLegder">
      <BasicInfoRef
        dicList={dicList}
        ref={basicInfoRef}
        groupList={groupList}
        id={id}
        actionType={ id ? 'edit' : 'add'}
      />
      <ArchivesRef
        id={id}
        ref={archivesRef}
        actionType={ id ? 'edit' : 'add'}
      />
      <div className="btnGroup">
        <Button type="primary" className="blue-button" onClick={() => submitData()}>
          提交审批
        </Button>
        <Button onClick={cancelLink}>取消</Button>
      </div>
    </div>
  );
}

export default connect(({ deviceLedger, dictionaryList, headerTaps, commonAction }) => ({
  deviceLedger,
  dictionaryList,
  headerTaps,
  commonAction
}))(withRouter(AddLegder));
